package cn.shop.dys.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import java.util.ArrayList;
import java.util.List;

import cn.shop.lib_common.CommonViewHolder;
import cn.shop.dys.R;

/**
 * 搜索适配器
 * Created by sunjian on 2016/4/9.
 */
public class SearchAdapter extends BaseAdapter implements Filterable {
    private Context mContext;
    private List<String> mSearchInfos;
    private List<String> mBackData;
    private MyFilter mFilter;
    public SearchAdapter(Context context, List<String> infos) {
        this.mContext = context;
        this.mSearchInfos = infos;
        this.mBackData=infos;
    }

    @Override
    public int getCount() {
        return mSearchInfos==null?0:mSearchInfos.size();
    }

    @Override
    public String getItem(int position) {
        return mSearchInfos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CommonViewHolder holder = CommonViewHolder.getCommonViewHolder(convertView, mContext, R.layout.item_lv_search_list);
        holder.getTv(R.id.tv_search_item).setText(mSearchInfos.get(position));
        return holder.convertView;
    }
    @Override
    public Filter getFilter() {
        if (null == mFilter) {
            mFilter = new MyFilter();
        }
        return mFilter;
    }

    // 自定义Filter类
    class MyFilter extends Filter {
        @Override
        // 该方法在子线程中执行
        // 自定义过滤规则
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            List<String> newValues = new ArrayList<String>();
            String filterString = constraint.toString().trim()
                    .toLowerCase();

            // 如果搜索框内容为空，就恢复原始数据
            if (TextUtils.isEmpty(filterString)) {
                newValues = mBackData;
            } else {
                // 过滤出新数据
                for (String str : mBackData) {
                    if (-1 != str.toLowerCase().indexOf(filterString)) {
                        newValues.add(str);
                    }
                }
            }

            results.values = newValues;
            results.count = newValues.size();

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      Filter.FilterResults results) {
            mSearchInfos = (List<String>) results.values;

            if (results.count > 0) {
                notifyDataSetChanged();  // 通知数据发生了改变
            } else {
                notifyDataSetInvalidated(); // 通知数据失效
            }
        }
    }
}
